const Role = require('../models/role');
const User = require('../models/user');

const requirePermission = (permission = []) => {
    return async (req, res, next) => {
        const newPermission = []
        if (!Array.isArray(permission)) {
            newPermission.push(permission)
        } else {
            newPermission.push(...permission)
        }
        const { userId } = req.user
        const user = await User.findById(userId);
        const { permissions,active } = await Role.findById(user.role)
        if (!active) {
            return res.status(201).json({
                code: 201,
                message: '角色已禁用'
            });
        }
        if (!newPermission.every(item => permissions.includes(item))) {
            return res.status(201).json({
                code: 201,
                message: '权限不足'
            });
        }
        if (newPermission.length === 0) {
            return res.status(201).json({
                code: 201,
                message: '权限不足'
            });
        }
        next();
    }
}

module.exports = {
    requirePermission
}